package org.example.erp.web.manager;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.erp.domain.SysMenu;
import org.example.erp.domain.SysUser;
import org.example.erp.mapper.SysMenuMapper;
import org.example.erp.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class DbUserDetailsManager implements UserDetailsService {
    private SysUserMapper sysUserMapper;
    @Autowired
    public void setSysUserMapper(SysUserMapper sysUserMapper) {
        this.sysUserMapper = sysUserMapper;
    }

    @Autowired
    private SysMenuMapper sysMenuMapper;


    // 基于数据库用户认证
    // 加载用户，核心方法 实现UserDetailsManager, UserDetailsPasswordService这两个接口也可以
    // 参考InMemoryUserDetailsManager，基于内存用户认证
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", username);
        queryWrapper.eq("status",0); //状态正常
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }else{
            //此User是springSecurity框架提供的，有两个构造方法
            //根据用户名查询菜单并把权限标识提取出来设置到用户的权限列表
            List<SysMenu> menus = sysMenuMapper.findMenus(username,null);
            List<String> perms =  menus.stream().filter(item-> item.getPerms()!=null)
                    .map(SysMenu::getPerms)
                    .collect(Collectors.toList());
//            System.out.println("list=====" + perms);
            // 查询当前用户的角色信息
            return new User(username,sysUser.getPassword(), AuthorityUtils.createAuthorityList(perms.toArray(new String[0])));
        }
    }
}
